package net.ankao.job.common.route;

import net.ankao.job.entity.AkApplicationClient;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 最不经常使用策略
 * @author LILU
 * @date 2024-12-04 9:14
 */
@Component
public class LeastFrequentlyUsedStrategy implements ClientRouteStrategy {

    // 为每个applicationId维护独立的使用计数
    private Map<String, Map<String, Integer>> usageCountMap = new ConcurrentHashMap<>();

    @Override
    public Integer strategyCode() {
        return 5;
    }

    @Override
    public List<AkApplicationClient> route(List<AkApplicationClient> clients) {
        if (clients == null || clients.isEmpty()) {
            return null;
        }

        String applicationId = clients.get(0).getApplicationId();
        Map<String, Integer> usageCount = usageCountMap.computeIfAbsent(applicationId, k -> new ConcurrentHashMap<>());

        return Arrays.asList(clients.stream()
                .filter(client -> client.getStatus() == 1)
                .min(Comparator.comparingInt(client ->
                        usageCount.getOrDefault(client.getId(), 0)))
                .map(client -> {
                    usageCount.merge(client.getId(), 1, Integer::sum);
                    return client;
                })
                .orElse(null));
    }
}
